import angular from 'angular';
import loadingTemplate from './ng-loading.template.html';

function ngLoadingDirective($compile, $timeout) {
  return {
    restrict: 'A',
    scope: {
      ngLoading: '=',
      loadingText: '@',
      loadingColor: '@',
      loadingSize: '@'
    },
    link: function(scope, element, attrs) {
      var loadingElement = null;
      var childScope = null;
      var originalPosition = null;

      // 确保父元素有定位上下文
      function ensurePositioned() {
        originalPosition = element.css('position');
        if (originalPosition === 'static' || !originalPosition) {
          element.css('position', 'relative');
        }
      }

      // 创建 loading 元素
      function createLoading() {
        childScope = scope.$new();

        // 设置配置
        childScope.config = {
          text: scope.loadingText || '',
          color: scope.loadingColor || '#1890ff',
          size: scope.loadingSize || 'medium'
        };
        childScope.visible = false;
        childScope.isDirective = true; // 标记为指令模式

        loadingElement = $compile(loadingTemplate)(childScope);
        element.append(loadingElement);

        // 延迟显示以触发动画
        $timeout(function() {
          if (childScope) {
            childScope.visible = true;
          }
        }, 10);
      }

      // 移除 loading 元素
      function removeLoading() {
        if (!loadingElement || !childScope) {
          return;
        }

        childScope.visible = false;

        $timeout(function() {
          if (loadingElement) {
            loadingElement.remove();
            loadingElement = null;
          }
          if (childScope) {
            childScope.$destroy();
            childScope = null;
          }
        }, 300);
      }

      // 监听 ngLoading 的变化
      scope.$watch('ngLoading', function(newVal) {
        if (newVal) {
          ensurePositioned();
          if (!loadingElement) {
            createLoading();
          }
        } else {
          removeLoading();
        }
      });

      // 监听可选属性的变化
      scope.$watch('loadingText', function(newVal) {
        if (childScope && childScope.config) {
          childScope.config.text = newVal || '';
        }
      });

      scope.$watch('loadingColor', function(newVal) {
        if (childScope && childScope.config) {
          childScope.config.color = newVal || '#1890ff';
        }
      });

      scope.$watch('loadingSize', function(newVal) {
        if (childScope && childScope.config) {
          childScope.config.size = newVal || 'medium';
        }
      });

      // 清理
      scope.$on('$destroy', function() {
        if (loadingElement) {
          loadingElement.remove();
        }
        if (childScope) {
          childScope.$destroy();
        }
      });
    }
  };
}

ngLoadingDirective.$inject = ['$compile', '$timeout'];

export default ngLoadingDirective;
